package com.um.jdy.common.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.um.jdy.common.system.dao.RoleButtonDao;
import com.um.jdy.common.system.dao.RoleDao;
import com.um.jdy.common.system.dao.RoleMenuDao;
import com.um.jdy.common.system.entity.po.Role;
import com.um.jdy.common.system.service.RoleService;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.service.BaseEntityServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * 服务实现类：系统角色表
 */
@Service
@Transactional
@Slf4j
public class RoleServiceImpl extends BaseEntityServiceImpl<RoleDao, Role>  implements RoleService{

    @Autowired
    RoleMenuDao roleMenuDao;

    @Autowired
    RoleButtonDao roleButtonDao;

    /**
     * 读取角色的菜单
     *
     * @param roleId
     * @return
     */
    @Override
    public Response getMenuTree(String roleId) {

        List lstAllButton = commonDao.queryList("sys_button", new Object[]{}, new Object[]{}, new Object[]{"sort_no"}, new Object[]{"asc"});

        List<Map> lstAllMenu = commonDao.queryLikeList("sys_menu", new Object[]{},new Object[]{},  new Object[]{"sys_menu_parent_id","sort_no"}, new Object[]{"asc","asc"});

        List lstSelected = commonDao.queryListBySQLName("get_role_menu",new Object[]{roleId});

        List lstButtonSelected = commonDao.queryListBySQLName("get_role_button",new Object[]{roleId});

        Map<String,String> mapSelected = new Hashtable<String,String>();
        for(Object item : lstSelected){
            mapSelected.put(((Map)item).get("sys_menu_id").toString(), ((Map)item).get("sys_menu_id").toString());
        }

        Map<String,String> mapButtonSelected = new Hashtable<String,String>();
        for(Object item : lstButtonSelected){
            mapButtonSelected.put(((Map)item).get("sys_button_id").toString(), ((Map)item).get("sys_button_id").toString());
        }


        StringBuffer sb = new StringBuffer();
        Map root = commonDao.queryMap("sys_menu", "sys_menu_id", "0");
        processNode(sb,lstAllMenu,root,mapSelected,lstAllButton,mapButtonSelected);

        String treeJSON = sb.toString();
        treeJSON = "["+treeJSON.substring(0, treeJSON.length()-1)+"]";
        JSONArray array = JSON.parseArray(treeJSON);
        return Response.success(array);
    }


    // 添加节点头部元素
    private void begin(StringBuffer sb, Map menu,Map<String,String> mapSelectMenu) {
        if (menu == null)
            return;
        sb.append("{ \"title\":\"");
        sb.append(menu.get("name"));
        sb.append("\",\"id\":\"");
        sb.append(menu.get("sys_menu_id"));
        sb.append("\",\"type\":\"");
        sb.append("menu");
        sb.append("\",\"parent_id\":\"");
        sb.append(menu.get("sys_menu_parent_id"));
        sb.append("\",\"selected\":");
        if(menu.get("sys_menu_id").equals("0")){
            sb.append("true");
        }else{
            if(mapSelectMenu.containsKey(menu.get("sys_menu_id"))==true){
                sb.append("true");
                mapSelectMenu.remove(menu.get("sys_menu_id"));
            }
            else{
                sb.append("false");
                mapSelectMenu.remove(menu.get("sys_menu_id"));
            }
        }
        sb.append(",\"nodes\":[");
    }

    // 递归处理每个机构节点及其子节点
    @SuppressWarnings("unchecked")
    private void processNode(StringBuffer sb, List<Map> lstMenu, Map menu,Map<String,String> mapSelectMenu,List<Map> lstAllAuthorityButton,Map<String,String> mapSelectAuthorityButton) {
        begin(sb, menu,mapSelectMenu);
        addAuthorityButton(sb,menu,lstAllAuthorityButton,mapSelectAuthorityButton);

        int length = lstMenu.size();
        for (int j = 0; j < length; j++) {
            Map subMenu = lstMenu.get(j);
            if(subMenu.get("sys_menu_parent_id") == null || subMenu.get("sys_menu_parent_id").equals(""))
                continue;
            if (subMenu.get("sys_menu_parent_id").equals(menu.get("sys_menu_id"))) {
                processNode(sb, lstMenu, subMenu,mapSelectMenu,lstAllAuthorityButton,mapSelectAuthorityButton);
            }
        }
        end(sb);

    }

    public void addAuthorityButton(StringBuffer sb,Map menu,List<Map> lstAllAuthorityButton,Map<String,String> mapSelectAuthorityButton){
        for(Map mapButton:lstAllAuthorityButton){
            if(mapButton.get("sys_menu_id").toString().equals(menu.get("sys_menu_id").toString())){
                String buttonId = mapButton.get("sys_button_id").toString();
                sb.append("{ \"title\":\"");
                sb.append(mapButton.get("name"));
                sb.append("\",\"id\":\"");
                sb.append(mapButton.get("sys_button_id"));
                sb.append("\",\"type\":\"");
                sb.append("button");
                sb.append("\",\"parent_id\":\"");
                sb.append(menu.get("sys_menu_id"));
                sb.append("\",\"selected\":");
                if(mapSelectAuthorityButton.containsKey(buttonId)){
                    sb.append("true");
                    mapSelectAuthorityButton.remove(buttonId);
                }else{
                    sb.append("false");
                    mapSelectAuthorityButton.remove(buttonId);
                }
                sb.append(",\"nodes\":[]},");
            }
        }
    }

    // 添加节点结尾元素
    private void end(StringBuffer sb) {
        sb.append("]},");
    }

}
